import React, { Component } from 'react';
import {Button,Table ,Divider ,Form, Input,Popconfirm,Icon} from 'antd';
import BasicConfirm from "../../components_yyr/common/basicConfirm";

const EditableContext = React.createContext();

class EditableCell extends React.Component {
	getInput = () => {
	  return <Input />;
	};
  
	renderCell = ({ getFieldDecorator }) => {
	  const {
		editing,
		dataIndex,
		title,
		inputType,
		record,
		index,
		children,
		...restProps
	  } = this.props;
	  return (
		<td {...restProps}>
		  {editing ? (
			<Form.Item style={{ margin: 0 }}>
			  {getFieldDecorator(dataIndex, {
				rules: [
				  {
					required: true,
					message: `Please Input ${title}!`,
				  },
				],
				initialValue: record[dataIndex],
			  })(this.getInput())}
			</Form.Item>
		  ) : (
			children
		  )}
		</td>
	  );
	};
  
	render() {
	  return <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>;
	}
  }

class App extends Component {
	state = { 
		loading: false, //加载中...
		dataSource: [], //数据源
		editingKey:'',
		key: Date.parse(new Date()),
    parentId:'',
    column:[]
 };
	componentDidMount() {
    this.props.onRef(this);
		let {column,editTableData}=this.props;
	
    column.push(
    {
      title: '操作',
        render:(text,record)=>{
        const { editingKey } = this.state;
        const editable = this.isEditing(record);
        return editable ? (
          <span>
          <EditableContext.Consumer>
            {form => (
            <a href
              onClick={() => this.saveRow(form,record.id)}
              style={{ marginRight: 8 }}
            >
              保存
            </a>
            )}
          </EditableContext.Consumer>
          <Popconfirm title="确认取消?" onConfirm={() => this.cancel(record.id)}>
            <a href>取消</a>
          </Popconfirm>
          </span>
        ) : (
          <span  disabled={editingKey !== ''}>
          <a href onClick={() => this.edit(record.id)}>
          修改
          </a>
          <Divider type="vertical" />
          <BasicConfirm title='确认删除?' button={false} buttonName='删除' data={record}  handleConfirm={this.handleConfirm}/>
          </span>
        )
      }
    });
   this.setState({
		column,dataSource:editTableData
   })
	}
		//this.props.editTableData 原始数据   newProps.editTableData //新数据  
		componentWillReceiveProps(newProps) {
			const {editTableData}=this.props;
			if(newProps.editTableData.length){
				let flag=false;
				for(let i=0;i<(editTableData.length>newProps.editTableData.length?newProps.editTableData.length:editTableData.length);i++){
					if(editTableData[i].id===newProps.editTableData[i].id){
						flag=true;
					}
				}
				if(!flag){
					this.setState({dataSource:newProps.editTableData})
				}
			}
		}
		isEditing = record => record.id === this.state.editingKey;

		edit=(key)=> {
			this.setState({ editingKey: key });
		}

		cancel = () => {
			this.setState({ editingKey: '' });
		};

		saveRow=(form,key)=>{
      form.validateFields((error, row) => {
        if (error) {
          return;
				}
				const newData = [...this.state.dataSource];
        const index = newData.findIndex(item => key === item.id);
        if (index > -1) {
					const item = newData[index];
          newData.splice(index, 1, {
            ...item,
            ...row,
					});
          this.setState({ dataSource: newData, editingKey: '' });
        } 
      });
		}

		handleConfirm	=	(value,api,chooseData)=>{
          let dataSource=this.state.dataSource.filter(item=>item.id!==chooseData.id)
					this.setState({
						dataSource
					})
		}

		tableData=()=>{
			return this.state.dataSource;
		}

		handleAdd = () => {
			const { key, dataSource } = this.state;
			const {column}=this.props;
			let newData = {}
			column.map(item=>newData[item.dataIndex]='');
			newData.id=key;
			this.setState({
				dataSource: [...dataSource, newData],
				key: Date.parse(new Date()),
			});
		};


	render() {
   
    const {loading,dataSource,column}=this.state;
				
		const components = {
			body: {
				cell: EditableCell,
			},
		};
		const columns = column.map(col => {
			if (!col.editable) {
				return col;
			}
			return {
				...col,
				onCell: record => ({
				record,
				inputType: col.dataIndex === 'age' ? 'number' : 'text',
				dataIndex: col.dataIndex,
				title: col.title,
				editing: this.isEditing(record),
				}),
			};
		});
	
		return (
			<div>
						
							<EditableContext.Provider value={this.props.form}>
                <Table 
                        dataSource={dataSource}
											 loading={loading}
											 components={components}
											 columns={columns}
											 rowKey={(record) => record.id}
											 pagination={false}
								/>
								</EditableContext.Provider>

								<Button type="dashed" onClick={this.handleAdd} style={{ width: '100%',marginTop:10 }}>
									<Icon type="plus" />添加
								</Button>
			</div>
		);
	}
}
export default Form.create()(App);